import java.util.ArrayList;
import java.util.List;

public class ThreadDemo10 {
    public static final int MAX_CAPCITY = 200;// 常量

    public static void main(String[] args) {
        List<String> datas = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Produce p = new Produce(datas);
            p.start();
        }

        for (int i = 0; i < 2; i++) {
            Consumer c = new Consumer(datas);
            c.start();
        }

    }
}


// 生产者
class Produce extends Thread {
    private List<String> datas;

    public Produce(List<String> datas) {
        this.datas = datas;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (datas) {
                if (datas.size() >= ThreadDemo10.MAX_CAPCITY) {
                    try {
                        datas.wait();// 必须得抢夺锁的锁调用wait，否则报错。
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    datas.add("1");
                    System.out.println(Thread.currentThread().getName() + "生产了1个包子，当前容量的个数为" + datas.size());
                    datas.notifyAll();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

// 消费者线程
class Consumer extends Thread {
    private List<String> datas;

    public Consumer(List<String> datas) {
        this.datas = datas;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (datas) {
                if (datas.size() <= 0) {
                    try {
                        datas.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    datas.remove("1");
                    System.out.println(Thread.currentThread().getName() + "消费了1个包子，当前容量的个数为" + datas.size());
                    datas.notifyAll();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
